//
//  BindPhoneViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/11.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class BindPhoneViewController: KMViewController {

    fileprivate let bindPhoneView = BindPhoneView()
    
    fileprivate var timer : Timer! //验证码计时器
    fileprivate var sounds = 60 //计时器当前秒数
    
    fileprivate var codeNumber = "" //验证码
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = bindPhone
        
        createSubView()
    }
    
    deinit {
        
        if timer != nil {
            sounds = 60
            self.bindPhoneView.phoneCodeBtn.setTitle(getCode, for: .normal)
            self.bindPhoneView.phoneCodeBtn.isEnabled = true
            timer.invalidate()
            timer = nil
        }
    }
    
    //MARK: 创建子视图
    fileprivate func createSubView() {
        
        self.getImageCode()
        bindPhoneView.imageCodeBtn.addTarget(self, action: #selector(getImageCode), for: .touchUpInside)
        bindPhoneView.phoneCodeBtn.addTarget(self, action: #selector(getPhoneCode), for: .touchUpInside)
        bindPhoneView.confirmBtn.addTarget(self, action: #selector(confirmBinding), for: .touchUpInside)
        self.view.addSubview(bindPhoneView)
        
        bindPhoneView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        
        getBindPhone()
        
    }
    
    //MARK: 获取图片验证码
    @objc fileprivate func getImageCode() {
        
        self.codeNumber = ""
        
        //移除旧的验证码图标
        for view in self.bindPhoneView.imageCodeBtn.subviews {
            view.removeFromSuperview()
        }
        
        let codeView = UIView()
        codeView.isUserInteractionEnabled = false
        codeView.backgroundColor = randomColor()
        self.bindPhoneView.imageCodeBtn.addSubview(codeView)
        
        codeView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        //数据源
        let array = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        
        //label的x坐标区间
        let counts = [25,30,30,25]
        let counts2 = [0,15,35,55]
        
        //显示验证码的label
        for i in 0...3 {
            
            let count = Int(arc4random())%array.count
            
            codeNumber += array[count]
            
            let label = UILabel()
            label.text = array[count]
            label.textColor = randomColor()
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: RATIO(maxNum: 25))
            codeView.addSubview(label)
            
            let y = arc4random()%10
            let x = Int(arc4random())%counts[i] + counts2[i]
            
            label.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(RATIO_H(maxNum: CGFloat(y)))
                make.left.equalToSuperview().offset(RATIO(maxNum: CGFloat(x)))
                make.height.equalTo(RATIO_H(maxNum: 25))
                make.width.equalTo(RATIO(maxNum: 25))
            }
        }
        
        //显示的线条数
        let lineCount:Int = Int(arc4random()%4)
        
        
        for _ in 0...lineCount {
            
            //线条的坐标点
            let pointAY = arc4random()%UInt32(RATIO_H(maxNum: 35))
            let pointAX = arc4random()%UInt32(RATIO_H(maxNum: 80))
            let pointBY = arc4random()%UInt32(RATIO_H(maxNum: 35))
            let pointBX = arc4random()%UInt32(RATIO_H(maxNum: 80))
            
            let pointA = CGPoint.init(x: CGFloat(pointAX), y: CGFloat(pointAY))
            let pointB = CGPoint.init(x: CGFloat(pointBX), y: CGFloat(pointBY))
            
            //通过CAShapeLayer和贝塞尔曲线绘制直线
            let layer = CAShapeLayer()
            let path = UIBezierPath()
            
            path.move(to: pointA)
            path.addLine(to: pointB)
            layer.lineWidth = 1
            layer.path = path.cgPath
            layer.strokeColor = randomColor().cgColor
            codeView.layer.addSublayer(layer)
        }
        
        
       
    }
    
    //MARK: 生成随机颜色
    fileprivate func randomColor()->UIColor {
        
        let r = arc4random()%255
        let g = arc4random()%255
        let b = arc4random()%255
        
        let color = UIColor.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1)
        return color
    }
    
    //MARK: 获取手机验证码
    @objc fileprivate func getPhoneCode() {
        
        if bindPhoneView.rebindView.text == "" {
            KMTool.showText(_text: inputBindPhone)
            return
        }
        
        
        KMTool.requestMethod(.post, URLString: url_signInCode, parameters: ["user_name":bindPhoneView.rebindView.text!], success: { (value, json) in
            
            if json["status"].stringValue == "0" {
                self.bindPhoneView.phoneCodeBtn.isEnabled = false
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.waitForPhoneCode), userInfo: nil, repeats: true)
                //添加至子线程
                RunLoop.main.add(self.timer, forMode: .commonModes)
            }
            
            KMTool.showText(_text: json["msg"].stringValue)
            
        }) {
            
        }
    }
    
    //MARK: 等待验证码
    @objc fileprivate func waitForPhoneCode() {

        sounds -= 1
        self.bindPhoneView.phoneCodeBtn.setTitle("\(sounds)", for: .normal)
        if sounds == 0 {
            sounds = 60
            self.bindPhoneView.phoneCodeBtn.setTitle(getCode, for: .normal)
            self.bindPhoneView.phoneCodeBtn.isEnabled = true
            timer.invalidate()
            timer = nil
        }
        
    }
    
    //MARK: 确认绑定
    @objc fileprivate func confirmBinding() {
        
        if bindPhoneView.rebindView.text == "" {
            KMTool.showText(_text: inputBindPhone)
            return
        }
        
        if bindPhoneView.imageCodeView.text == "" {
            KMTool.showText(_text: inputImageCode)
            return
        }
        
        if bindPhoneView.phoneCodeView.text == "" {
            KMTool.showText(_text: inputPhoneCode)
            return
        }
        
        //验证码对比，不区分大小写
        if bindPhoneView.imageCodeView.text!.lowercased().replacingOccurrences(of: " ", with: "") != codeNumber.lowercased() {
            KMTool.showText(_text: codeError)
        }
        
        cheakPhoneCode()
    }
    
    
    //MARK: 判断验证码是否正确
    fileprivate func cheakPhoneCode() {
        
        KMTool.requestMethod(.get, URLString: url_bindPhoneCode, parameters: ["psw":"kameng98_loan","code":bindPhoneView.phoneCodeView.text ?? "","phone":bindPhoneView.rebindView.text ?? ""], success: { (value, json) in
            
            if json["status"].stringValue == "0" {
                self.bindPhoneAction()
            }else{
                
                KMTool.showText(_text: json["msg"].stringValue)
            }
            
            
        }) {
            
        }
    }
    
    //MARK: 绑定手机
    fileprivate func bindPhoneAction() {
        
        KMTool.waiting()
        KMTool.requestGetData(URLString: url_bindPhone, parameters: ["psw":"kameng98_loan","type":"2","userid":KMTool.stringForEnumKey(.phone) ?? "","phone":bindPhoneView.rebindView.text ?? ""], success: { (data) in
            
            KMTool.stop()
            
            //数据解析
            let string = NSString.init(data: data , encoding: String.Encoding.utf8.rawValue)! as String
            KMTool.showText(_text: string)
            
            if string == changeSuccess {
                self.navigationController?.popViewController(animated: true)
            }
        }) {
            
        }
        
        
        
    }
    
    //MARK: 获取绑定手机号码
    fileprivate func getBindPhone() {
        
        KMTool.requestGetData(URLString: url_bindPhone, parameters: ["psw":"kameng98_loan","type":"1","userid":KMTool.stringForEnumKey(.phone) ?? ""], success: { (data) in
            //数据解析
            let string = NSString.init(data: data , encoding: String.Encoding.utf8.rawValue)! as String
            
            self.bindPhoneView.phoneLabel.text = string.replacingOccurrences(of: "\"", with: "")
        }) {
            
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}
